package com.twoscreen;

import java.util.Random;
import java.util.logging.Logger;

import org.json.JSONObject;

import com.twoscreen.test.Test;
import com.twoscreen.test.TestMethod;

/**
 * @author James Smith
 */
public class CodeGenerator {
	private static final Logger log = Logger.getLogger("com.twoscreen.CodeGenerator.java");
	
	/**
	 * Generates a code based on the length entered
	 * Uses alphanumeric characters upper and lowercase
	 * Permutations = 62^n
	 * @param idLength The required length of the code
	 * @return The code generated
	 */
	protected static String createID(int idLength) {
		log.info("Creating an ID");
		String id = "";
		String characters = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789"; //62
		Random random = new Random();
		
		while (id.length() < idLength) {
			int randNo = random.nextInt(characters.length());
			char randLetter = characters.charAt(randNo);
			id += randLetter;
		}
		
		log.info("Returning an ID");
		return id;
	}
	
	/**
	 * Runs all the tests on the class
	 * @return Test results JSON
	 */
	public static JSONObject test() {
		Test test = new Test("CodeGenerator");
		test.addMethod(testGenerateId());
		return test.getJSONObject();
	}
	
	/**
	 * Tests the generateId method
	 * @return Test results JSON
	 */
	private static JSONObject testGenerateId() {
		TestMethod tm = new TestMethod("testGenerateId");
		
		//Test base
    	String code = CodeGenerator.createID(6);
    	
		//Test 1
		Boolean test1 = false;
    	String testStack1 = "";
    	try {
    		test1 = (code.length() == 6);
    	} catch (Exception e) {
    		testStack1 = e.getMessage();
    	}
		tm.addTest("Length check", test1, testStack1);
		
		//Test 2
		Boolean test2 = false;
    	String testStack2 = "";
    	try {
    		test2 = (code.matches("^[A-z0-9]+$"));
    	} catch (Exception e) {
    		testStack2 = e.getMessage();
    	}
    	tm.addTest("Alphanumeric check", test2, testStack2);
    	
    	return tm.getJSONObject();
    }
	
}
